package com.ivan.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ivan.beans.Message;
import com.ivan.message.MessagesPool;

public class UpdateMessagesToClient extends HttpServlet {
	
	private static final long serialVersionUID = 4841161358580314165L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String datePos = req.getParameter("pos");
		Map<Long, List<Message>> result = MessagesPool.getMessageByDate(Long.parseLong(datePos));
		StringBuffer output = new StringBuffer();
		output.append("[");
		for(Long key : result.keySet()){
			output.append("{ pos: '")
			.append(String.valueOf(key))
			.append("', history: \"")
			.append(MessagesPool.generateTextForClient(result.get(key)))
			.append("\" }");
		}
		output.append("]");
		resp.setContentType("plain/text;charset=UTF-8");
		PrintWriter writer = resp.getWriter();
		writer.write(output.toString());
		System.out.println("Updated: " + output.toString());
		writer.flush();
		writer.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}	
	
}
